package com.imooc.reader.management.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.imooc.reader.management.dto.ResponseDTO;
import com.imooc.reader.management.entity.Book;
import com.imooc.reader.management.service.BookService;
import com.imooc.reader.management.service.impl.exception.BusinessException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/books")
public class BookController {
    @Resource
    private BookService bookService;
    @Value("${upload.dir}")
    private String uploadDir;

    @GetMapping("")
    public ResponseDTO list(Integer page, Integer rows) {
        if (page == null) {
            page = 1;
        };
        if (rows == null) {
            rows = 10;
        }
        IPage p = bookService.selectBookMap(page, rows);
        return new ResponseDTO().put("list", p.getRecords()).put("count", p.getTotal());
    }

    @PostMapping("")
    public ResponseDTO createBook(Book book) {
        System.out.println(book.getDescription());
        Document doc = Jsoup.parse(book.getDescription());
        Elements elements = doc.select("img");
        if (elements.size() == 0) {
            throw new BusinessException("ImageNotFoundError", "图书描述未包含封面图片");
        }
        String cover = elements.first().attr("src");
        book.setCover(cover);
        book.setEvaluationScore(0f);
        book.setEvaluationQuantity(0);
        Book b = bookService.createBook(book);
        return new ResponseDTO().put("book", b);
    }

    @PutMapping("/{bookId}")
    public ResponseDTO updateBook(@PathVariable("bookId") Long bookId, Book book) {
        Document doc = Jsoup.parse(book.getDescription());
        Elements elements = doc.select("img");
        if (elements.size() == 0) {
            throw new BusinessException("ImageNotFoundError", "图书描述未包含封面图片");
        }
        String cover = elements.first().attr("src");
        book.setCover(cover);
        Book b = bookService.updateBook(book);
        return new ResponseDTO().put("book", b);
    }

    @DeleteMapping("/{bookId}")
    public ResponseDTO deleteBook(@PathVariable("bookId") Long bookId) {
        ResponseEntity<ResponseDTO> resp = null;
        bookService.deleteBook(bookId);
        return new ResponseDTO();
    }

    @PostMapping("/images")
    public Map upload(@RequestParam("img") MultipartFile file , HttpServletRequest request) throws IOException {
        File imageDir = new File(uploadDir + "/images");
        if(!imageDir.exists()){
            imageDir.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = sdf.format(new Date());
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        file.transferTo(new File(imageDir.getAbsoluteFile() +"/"+fileName + suffix));
        Map result = new LinkedHashMap();
        result.put("errno", 0);
        result.put("data", new String[]{"/images/" + fileName + suffix});
        return result;
    }

    @GetMapping("/set")
    public String setSession(HttpSession session) {
        session.setAttribute("username", "user123");
        return "Session data set";
    }
}


